package com.xugui.learn.pay.strategy;

import com.xugui.learn.pay.pojo.enums.PayChannel;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 支付策略工厂
 */
@Component
public class PayStrategyFactory {

    private final Map<PayChannel, PayStrategy> strategyMap = new ConcurrentHashMap<>();

    public PayStrategyFactory(List<PayStrategy> strategies) {
        for (PayStrategy strategy : strategies) {
            strategyMap.put(strategy.getPayChannel(), strategy);
        }
    }

    /**
     * 根据支付渠道获取对应的支付策略
     *
     * @param payChannel 支付渠道
     * @return 支付策略
     */
    public PayStrategy getStrategy(PayChannel payChannel) {
        PayStrategy strategy = strategyMap.get(payChannel);
        if (strategy == null) {
            throw new RuntimeException("不支持的支付渠道：" + payChannel.getName());
        }
        return strategy;
    }

    /**
     * 根据支付渠道代码获取对应的支付策略
     *
     * @param channelCode 支付渠道代码
     * @return 支付策略
     */
    public PayStrategy getStrategy(String channelCode) {
        PayChannel payChannel = PayChannel.getByCode(channelCode);
        if (payChannel == null) {
            throw new RuntimeException("不支持的支付渠道代码：" + channelCode);
        }
        return getStrategy(payChannel);
    }
}
